package p.ithorns.framework.common.thread;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * CurrentTimeMillisClock
 * <p>
 * System.currentTimeMillis() 性能改进
 *
 * @author ithorns
 * @version 1.0
 * @date 2020/5/23 22:47
 */
public class SystemClock {

    private final AtomicLong now;

    private SystemClock() {
        now = new AtomicLong(System.currentTimeMillis());
        scheduleTick();
    }

    private void scheduleTick() {
        ThreadFactory threadFactory = ThreadPoolFactory.threadFactory("current-time-millis", true);
        ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1, threadFactory);
        scheduler.scheduleAtFixedRate(() -> {
            now.set(System.currentTimeMillis());
        }, 1, 1, TimeUnit.MILLISECONDS);
    }

    public static long now() {
        return instance().now.get();
    }

    private static class SingletonHolder {
        private final static SystemClock INSTANCE = new SystemClock();
    }

    public static SystemClock instance() {
        return SingletonHolder.INSTANCE;
    }

}
